package com.github.caijinglong

import com.alibaba.fastjson.JSON
import com.github.caijinglong.bean.SaveData
import org.json.JSONArray
import org.json.JSONObject
import java.io.FileInputStream
import java.io.FileOutputStream
import java.nio.charset.Charset
import java.util.*
import kotlin.experimental.xor

fun main(args: Array<String>) {
//    val txt = FileInputStream("IRONCLAD.autosave").bufferedReader().readText()
    val txt = FileInputStream("./f/src.txt").bufferedReader().readText()
    val handler = Handler()
    val message = handler.decode(txt)
    println(message)
    val data = JSON.parseObject(message, SaveData::class.java)
    val obj = JSONObject(message)

//    handle(data)
    handle(obj)
//    val target = JSON.toJSONString(data)
    val target = obj.toString()
    println(target)

////    for (i in 0..obj.length()) {
//    obj.toMap().forEach { k, v ->
//        println("key = [ $k ] value = [ $v ]")
//    }
////    }
//
//    val relics = obj.getJSONArray("relics")
//    println(relics)

//    return
    FileOutputStream("target.txt").bufferedWriter().apply {
        val encodeString = handler.encode(target)
        write(encodeString)
        flush()
    }
}

fun handle(data: JSONObject) {
//    data.getInt("max_health")
    data.put("max_health", 110)
    data.put("current_health", 110)
    data.put("gold", 4000)
    val obj = data.getJSONArray("relics")
    obj.put("White Beast Statue", "Meat on the Bone", "Matryoshka", "Black Star", "Sozu", "Tiny House")
}

private fun JSONArray.put(vararg values: String) {
    val list = this.toList()
    values.forEach {
        if (list.contains(it).not()) {
            this.put(it)
        }
    }
}

fun handle(data: SaveData) {
    data.max_health = 600
    data.gold = 65000
}

val key = "key"

fun decode(txt: String): String {
    val dStr = Base64.getDecoder().decode(txt)
    val buf = ByteArray(dStr.size)
    dStr.forEachIndexed { index, byte ->
        buf[index] = byte xor key[index % key.length].toByte()
    }
    return buf.toString(Charset.defaultCharset())
}

fun encode(txt: String): String {
    val buf = ByteArray(txt.toByteArray(Charset.defaultCharset()).size)
    println(txt.toByteArray().size)
    txt.toByteArray().forEachIndexed { index, byte ->
        println("index = $index byte = $byte")
        buf[index] = byte xor key[index % com.github.caijinglong.key.length].toByte()
    }
    return Base64.getEncoder().encode(buf).toString(Charset.defaultCharset())
}